package cn.xiaolang.function.json.jacksonVsRegex;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.util.StopWatch;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonReadRegexVsJsonUtils {

	private final static ObjectMapper mapper = new ObjectMapper();

	public static void main(String[] args) {
		String jsonstr = "{\"name\":\"xiaolang\",\"age\":89}";
		String jsonstr2 = "[{\"name\":\"xiaolang\",\"age\":89},{\"name\":\"fangfang\",\"age\":21}]";
		simpleJson(jsonstr, "name", 2000);
		collectionsJson(jsonstr2, "name", 100);
	}

	public static void simpleJson(String jsonstr, String fieldname, int size) {
		try {
			StopWatch s1 = new StopWatch("regex-simple-" + size);
			s1.start();
			for (int i = 0; i < size; i++) {
				JsonReadHelper.getValueByStrField(jsonstr, fieldname);
			}
			s1.stop();
			System.err.println(s1.prettyPrint());
			StopWatch s2 = new StopWatch("jackson-simple-" + size);
			s2.start();
			for (int i = 0; i < size; i++) {
				Map<String, Object> readValue = mapper.readValue(jsonstr, new TypeReference<Map<String, Object>>() {
				});
				readValue.get(fieldname);
			}
			s2.stop();
			System.err.println(s2.prettyPrint());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void collectionsJson(String jsonstr, String fieldname, int size) {
		try {
			StopWatch s1 = new StopWatch("regex-list-" + size);
			s1.start();
			for (int i = 0; i < size; i++) {
				JsonReadHelper.getListByStrField(jsonstr, fieldname);
			}
			s1.stop();
			System.err.println(s1.prettyPrint());
			StopWatch s2 = new StopWatch("jackson-list-" + size);
			s2.start();
			for (int i = 0; i < size; i++) {
				List<Map<String, Object>> readValue = mapper.readValue(jsonstr,
						new TypeReference<List<Map<String, Object>>>() {
						});
				readValue.stream().map(a -> a.get(fieldname)).collect(Collectors.toList());
			}
			s2.stop();
			System.err.println(s2.prettyPrint());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
